<template>
  <view class="commodity-scan">
    <eui-page-frame :topHeight="100" :withOutBorder="true" :bottomHeight="130">
      <template #top>
        <eui-navbar title="商品扫码" color="#303133" backgroundColor="#FFFFFF" rightIcon=''></eui-navbar>
      </template>
      
      <eui-page-content>
        <!-- 可以添加扫码相关的内容 -->
         <half-screen-scan-code @getCodeResult="getCodeResult"></half-screen-scan-code>

         <scroll-view class="scroll-view" scroll-y v-if="requestEnd">

           <eui-card :title="commodityInfo.c_name">
              <view class="item-view flex-row">
                <view
                  v-for="(optionItem, optionIndex) in commodityInfoOptions"
                  :key="optionIndex"
                  class="item-detail-view"
                  >
                  <text v-if="optionItem.label" class="item-text">{{ optionItem.label }}：</text>
                  <text class="item-text item-text-detail">{{ optionItem.beforeUnit }}{{ commodityInfo[optionItem.name] }}{{ optionItem.afterUnit }}</text>
                </view>
              </view>
           </eui-card>

            <!--  操作数量  -->
           <view class="handle-count-content flex-row-between">
             <view class="title">调拨数量</view>
             <eui-inputnumber
                 :value="commodityInfo.c_qtty"
                 :styletype="true"
                 placeholder="输入调拨数"
                 @input="changeValue"
             />
           </view>

           <!--  附近库存  -->
           <view class="near-stock-store">
             <view class="title flex-start-center">附近库存</view>
             <view class="stock-list">
              <stock-store-item
                 v-for="(item, index) in stockList"
                 :key="index"
                 :store-item="item"
                 background-color="#f2f3f5"
                 @handleApply="handleApply"
              >
              </stock-store-item>
             </view>
           </view>


         </scroll-view>



         

      </eui-page-content>

      <template #bottom>
        <goods-cart></goods-cart>
      </template>
    </eui-page-frame>
  </view>
</template>

<script setup lang="ts">
import { onShow, onLoad } from '@dcloudio/uni-app';
import { ref, watch } from 'vue'
import service from '@/common/service';
import { storeToRefs } from 'pinia';
import { useThemeStore } from '@/store/themeStore';
import goodsCart from './../components/goodsCart.vue';
import stockStoreItem from './../components/stockStoreItem.vue';
import HalfScreenScanCode from '../components/HalfScreenScanCode/index.vue';
import { useMainStore } from "@/store/modules/store";
import { getRdsUrl, rdsRequest } from "@/hooks/rdsServices";
import Enjoy from "@/common/enjoy";
import { useReceiptStore } from '@/store/useReceiptStore';

const themeStore = useThemeStore();
const { theme } = storeToRefs(themeStore);
const themeColor = ref(theme.value.theme=='theme-blue'?'#02B7E6':'#FF6430')

const mainStore = useMainStore();
const { loginInfo } = mainStore;
const rdsUrl = getRdsUrl();

const currentCommodityNo = ref('');
const commodityInfoOptions = ref([
  { label: '货号', name: 'c_gcode' },
  { label: '编码', name: 'c_barcode' },
  { label: '规格', name: 'c_model' },
  { label: '单位', name: 'c_content' },
  { label: '售价', name: 'c_price', beforeUnit: '¥' },
  { label: '保质期', name: 'c_price' },
  { label: '成本价', name: 'c_price', beforeUnit: '¥', afterUnit: '' },
]);
const currentLocation = ref({
  longitude: '112.575654',
  latitude: '37.743084'
});

const receiptStore = useReceiptStore();

onLoad(async()=>{
  getCodeResult('114370');
  Enjoy.GeolocationPosition('getCurrentPosition',position=>{
    if(position.coords.longitude&&position.coords.latitude){
      currentLocation.value = {
        longitude: position.coords.longitude,
        latitude: position.coords.latitude
      };
    }
  });
})

const commodityInfo = ref({})
const requestEnd = ref(false);

const getCodeResult = async (code: string) => {
  try {
    if (currentCommodityNo.value == code) {
      return;
    }
    requestEnd.value = false;
    currentCommodityNo.value = code;
    let request = {
      IsNotPage: false,
      PageSize: 20,
      CurrentPage: 1,
      Tag: '',
      StoreId: loginInfo.sUserStore,
      Gcode: code,
    };

    uni.showLoading({ title: "加载中...", mask: true });
    const result = await rdsRequest(rdsUrl.apiApi, '管易通60RMIS公共', 'GetGdsInfo', request);
    // const result = {
    //   "ReturnObject": [
    //     {
    //       "c_id": "PD12310070006",
    //       "c_gcode": "00332575",
    //       "c_barcode": "",
    //       "c_name": "老庙铂金",
    //       "c_model": "",
    //       "c_content": 1,
    //       "c_type": "专柜类品",
    //       "c_status": "正常流转",
    //       "c_pro_status": "普通商品",
    //       "c_sale_status": "正常销售",
    //       "c_price": 1,
    //       "c_price_disc": 0,
    //       "c_number": 0,
    //       "c_today_sale": null,
    //       "c_n_min": 0,
    //       "c_n_max": 0,
    //       "c_dnlmt_number": 0,
    //       "c_onway": 0,
    //       "c_to_ret": 0,
    //       "c_sn_perday_pro": 0,
    //       "c_dnlmt_day": 7,
    //       "c_sn_perday": 0,
    //       "c_n_min_order": null,
    //       "c_opl_prohibit": "不禁止",
    //       "c_week0": 0,
    //       "c_week1": 0,
    //       "c_week2": 0,
    //       "c_week3": 0,
    //       "c_week4": 0,
    //       "c_provider": "1000035",
    //       "c_provider_name": "宫玺珠宝（深圳）有限公司",
    //       "c_d_onway": null
    //     },
    //   ],
    //   "AggregateObject": null,
    //   "RowsCount": 63,
    //   "PageCount": 4,
    //   "CurrentPage": 1,
    //   "PageSize": 20,
    //   "ErrorString": null
    // };

    uni.hideLoading();
    
    // 获取商品信息并添加数量属性
    const newItem = result.ReturnObject.map(item => ({ ...item, c_qtty: 1 }))[0];
    console.log('newItem', newItem)
    // 查找购物车中是否已存在该商品
    const existingItem = receiptStore.cartList.find(item => item.c_gcode === newItem.c_gcode);
    
    if (existingItem) {
      // 如果购物车中已存在,同步购物车中的数量
      commodityInfo.value = {
        ...newItem,
        c_qtty: existingItem.c_qtty
      };
    } else {
      // 如果购物车中不存在,添加到购物车
      commodityInfo.value = newItem;
      receiptStore.addToCart(commodityInfo.value);
    }

    requestEnd.value = true;

    console.log('commodityInfo', commodityInfo.value)
    getNearStockStore();
  } catch (error) {
    console.log(error)
  }
}


// 库存列表数据
const stockList = ref<any[]>([]);

const getNearStockStore = async () => {
  try {
    uni.showLoading({ title: "加载中...", mask: true });
    const result = await rdsRequest(
      rdsUrl.apiApi,
      '管易通60RMIS商品调拨',
      'GetGpsStore',
      {
        Gcode: `${commodityInfo.value.c_gcode}@${commodityInfo.value.c_qtty}`,
        ...currentLocation.value
      }
    );
    uni.hideLoading();

    if (result) {
      stockList.value = result;
    }
  } catch (error) {
    console.error('获取附近库存失败:', error);
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    });
  }
}

const changeValue = (e: { detail: { value: number } }) => {
  if(commodityInfo.value.c_gcode) {
    commodityInfo.value.c_qtty = e.detail.value;
    
    receiptStore.updateCartItemQtty(commodityInfo.value.c_gcode, e.detail.value);
  }
}


import { useCommonPage } from '../hooks/useCommonPage';
const { checkRouteAndNavigate } = useCommonPage();

const handleApply = (storeItem: any) => {
  console.log('handleApply', storeItem)
  // 保存选中的门店信息到 receiptStore
  receiptStore.updateFromData('md', storeItem);
  
  checkRouteAndNavigate('pages/BusiViews/StoreTransfer/detail');
}

// 添加对 cartList 的监听
watch(
  () => receiptStore.cartList,
  (newCartList) => {
    // 如果当前有显示商品,则同步购物车中对应商品的数量
    if (commodityInfo.value?.c_gcode) {
      const cartItem = newCartList.find(item => item.c_gcode === commodityInfo.value.c_gcode);
      if (cartItem) {
        commodityInfo.value.c_qtty = cartItem.c_qtty;
        getNearStockStore();
      }
    }
  },
  { deep: true } // 深度监听数组变化
);

</script>

<style lang="scss" scoped>
.commodity-scan {
  ::v-deep .white-main{
    margin: 0;
    border-radius: 0;
  }

  ::v-deep .single-title {
    font-weight: bold;
    line-height: 40rpx;
  }

  .scroll-view {
    height: calc(100% - 580rpx);
    .item-view {
      flex-wrap: wrap;
      .item-detail-view {
        width: 50%;
        margin-bottom: 10rpx;
        font-size: 24rpx;
        text-align: left;
        color: #666666;
        line-height: 34rpx;
      }
    }

    .handle-count-content {
      height: 100rpx;
      margin: 20rpx;
      padding: 0 20rpx;
      background: #ffffff;
      border-radius: 16rpx;
    }
  }

  .near-stock-store {
    position: relative;
    margin: 20rpx;
    background: #ffffff;
    border-radius: 20rpx;
    padding: 30rpx 0;

    .title {
      width: 280rpx;
      height: 80rpx;
      margin-bottom: 20rpx;
      padding-left: 20rpx;
      background: linear-gradient(161deg, rgba(64, 158, 255, 0.06) 21%, rgba(255, 255, 255, 0.00) 98%);
      font-size: 30rpx;
      font-weight: bold;
      color: #222222;
      line-height: 42rpx;
    }

    .stock-list {
      padding: 0 20rpx;
    }
  }
}
</style>